#include "functions.h"
#include "version.h"
#include <QUrl>
#include <QString>

QString getVersion()
{
    QString str = "version: ";
    return str\
            + QString::number(MAJOR_VERSION) + "." \
            + QString::number(MINOR_VERSION) + "."\
            + QString::number(BUILD_VERSION) + "\n";
}

QString getTimeString(uint64 t)
{
    if(t < 1000)    // microseconds
    {
        return QString::number(t) + " microseconds";
    }

    t /= 1000;  // milliseconds
    if(t < 1000)
    {
        return QString::number(t) + " milliseconds";
    }

    t /= 1000;  // seconds
    if(t < 60)
    {
        return QString::number(t) + " seconds";
    }

    t /= 60;    // minutes
    if(t < 60)
    {
        return QString::number(t) + " minutes";
    }

    t /= 60;
    return QString::number(t) + " hours";
}

string getLine(char* &buf)
{
    string str;
    char c;
    while(true)
    {
        c = *buf;
        if(c == '\0')
        {
            buf++;
            return str;
        }
        if(c == '\r')
        {
            buf++;      // \r
            if(*buf == '\n')
                buf++;      // \n
            return str;
        }
        if(*buf == '\n')
        {
            buf++;      // \n
            return str;
        }

        str.push_back(c);
        buf++;
    }
    return str;
}

// path is already in decoded form
QString getFileName(const QString &path)
{
    auto last_slash = path.lastIndexOf('/');
    auto query = path.indexOf('?');
    QString name;
    if(query == -1) {
        name = path.mid(last_slash + 1);
    } else {
        name = path.mid(last_slash + 1, query - (last_slash + 1));
    }
    return name;
}

string getHeaderName(string s)
{
    return s.substr(0, s.find(':'));
}
